<?php

use App\Services\Common\DbConfigService;
use Illuminate\Support\Carbon;
use Maatwebsite\Excel\Facades\Excel;
use App\Libs\Blogger;

if (!function_exists('x')) {
    function x($data = [])
    {
        echo '<br/><pre><br/>';
        $data = print_r($data, true);
        echo $data . '<br/><pre><br/>';
        exit();
    }
}
//PHP stdClass Object转array
if (!function_exists('object_array')) {
    function object_array($array)
    {
        if (is_object($array)) {
            $array = (array)$array;
        }
        if (is_array($array)) {
            foreach ($array as $key => $value) {
                $array[$key] = object_array($value);
            }
        }
        return $array;
    }
}

/**
 * 密码加密
 */
if (!function_exists('md5Pwd')) {
    function md5Pwd($pwd = '', $salt = '')
    {
        return md5($pwd . md5($salt));
    }
}
/**
 * 简单的参数过滤
 */
if (!function_exists('val')) {
    function val($val, $type = 0)
    {
        $val = trim($val);
        if ($val == '') {
            return '';
        }
        if (!is_string("$val")) {
            return '';
        }

        switch ($type) {
            case 0:
                return addslashes(htmlspecialchars($val, ENT_QUOTES));
                break;
            case 1:
                return intval($val);
                break;
            case 2:
                return $val;
                break;
            default :
                break;
        }
    }
}


/**
 * 返回值输出
 * return $status请求状态［0请求失败 1请求成功］ $msg请求结果说明 $data请求结果 $errCode失败错误码
 **/
if (!function_exists('output')) {
    function output($status, $msg = '网络异常', $data = '', $errCode = '0')
    {
        return response()->json(['status' => intval($status), 'msg' => $msg, 'data' => $data, 'errCode' => intval($errCode)]);
    }
}
/**
 * 原生
 * 返回值输出
 */
if (!function_exists('nativeOutput')) {
    function nativeOutput($status, $msg = '网络异常', $data = '', $errCode = '0')
    {
        echo json_encode(['status' => intval($status), 'msg' => $msg, 'data' => $data, 'errCode' => intval($errCode)]);
        die();
    }
}

/**
 * return $status请求状态［0请求失败 1请求成功］ $msg请求结果说明 $data请求结果 $errCode失败错误码
 */
if (!function_exists('outputJson')) {
    function outputJson($status, $msg = '网络异常', $data = '', $errCode = '0')
    {
        return json_encode(['status' => intval($status), 'msg' => $msg, 'data' => $data, 'errCode' => intval($errCode)]);
    }
}

/**
 * 生成短信随机码
 */
if (!function_exists('generateSmsCode')) {
    function generateSmsCode()
    {
        return rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9) . rand(0, 9);
    }
}

/**
 * 设置cookie
 * data 的 key 作为 cookie 的 key, data 的 value 作为 cookie 的 value
 **/
if (!function_exists('setCookieData')) {
    function setCookieData($data = array())
    {
        foreach ($data as $key => $val) {
            \Cookie::queue($key, $val, 60 * 24 * 365);
        }
        return true;
    }
}
/**
 * 销毁cookie, value 为cookie 的key
 */
if (!function_exists('unsetCookieData')) {
    function unsetCookieData($data = array())
    {
        foreach ($data as $val) {
            \Cookie::queue($val, null, -1);
        }
        return true;
    }
}

/**
 * 创建随机码
 */
if (!function_exists('createCode')) {
    function createCode($namespace, $length)
    {
        static $gUid = '';
        $uid = uniqid("", true);
        $data = $namespace;
        $data .= $_SERVER['REQUEST_TIME'];
        $hash = strtoupper(hash('ripemd128', $uid . $gUid . md5($data)));
        $rand = rand(0, 5);
        $gUid = substr($hash, $rand, $length);
        return $gUid;
    }
}

/**
 * 订单号生成
 * $prefix 订单前缀说明： 1-用户支付订单号 2-用户提现订单号 3-批量付款订单号 4-积分流水号 5-交易流水号 6-充值订单 7-退款单 8-企业账单流水消费记录
 **/
if (!function_exists('createSn')) {
    function createSn($prefix = 1)
    {
//        return sprintf($prefix . "%s%05d", date('ymdHis'), rand(10000, 99999));
        $serverTime = time();
        return sprintf($prefix . "%s%06d%05d", date('ymdHis', $serverTime), substr(preg_replace('/[\s]+/', '', microtime()), 2, 6), rand(10000, 99999));
    }
}

/**
 * 回调统一日志
 */
if (!function_exists('logRecord')) {
    function logRecord($path, $word = '')
    {
        $logPath = LOG_PATH . $path;
        if (!is_dir($logPath)) {
            mkdir($logPath);
        }
        $file = $logPath . DIRECTORY_SEPARATOR . date('Y_m_d') . '.log';
        $fp = fopen($file, "a");
        flock($fp, LOCK_EX);
        fwrite($fp, "执行日期：" . strftime("%Y-%m-%d-%H：%M：%S", time()) . "\n" . $word . "\n\n");
        flock($fp, LOCK_UN);
        fclose($fp);
    }
}
/**
 * 获取登录者信息
 */
if (!function_exists('userInfo')) {
    function userInfo()
    {
        return $userInfo = request()->get('userInfoVerify');
    }
}
/**
 * 获取登录者信息
 */
if (!function_exists('getTeacherSchoolId')) {
    function getTeacherSchoolId()
    {
        return $userInfo = request()->get('teacher_school_id');
    }
}

/**
 *  判断数组里面的键值对是不是全是空值
 */
if (!function_exists('arrayValueIsAllNull')) {
    function arrayValueIsAllNull($array)
    {
        if (empty($array)) {
            return true;
        }
        foreach ($array as $item) {
            if (!empty($item)) {
                return false;
            }
        }
        return true;
    }
}


// 验证手机号
if (!function_exists('isMobile')) {
    function isMobile($mobile)
    {
        if (preg_match("/^1[3-9]{1}[0-9]{9}$/", $mobile)) {
            return true;
        } else {
            return false;
        }
    }
}

/**
 * hash编号
 * @param bool $long
 * @return string
 */
function hashId($long = false)
{
    $hash = new Hashids\Hashids('4Ptr2YT647LP64IpLuoBRbcy1UF0Jev611', 12, 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890');
    if ($long) {
        $rand = mt_rand(10000000, 99999999);
    } else {
        $rand = mt_rand(1000, 9999);
    }
    $num = (int)(time() . $rand);
    return $hash->encode($num);
}

/**
 * 获取字符中的纯数字
 */
if (!function_exists('getNumberInStr')) {
    function getNumberInStr($str)
    {
        $number = 0;
        if (preg_match('/\d+/', $str, $array)) {
            $number = $array[0];
        };
        return $number;
    }

}



if (!function_exists('isAdmin')) {
    function isAdmin()
    {
        $adminList = [
            "admin"
        ];
        $userInfo = userInfo();
        if (in_array($userInfo->users_name, $adminList) && $userInfo->relation_id == -2){
            return 1;
        }
//        if ($userInfo->identity == -1){
//            return 1;
//        }
        return 0;
    }
}

/**
 * 读取excel
 */
if (!function_exists('readExcel')) {
    function readExcel($excel)
    {
        ini_set('memory_limit', '2048M');
        /** @var  $collection */
        $collection = Excel::toCollection(new \App\Models\ImportBaseModel(), $excel)->getIterator();
        $newCollection = collect([]);
        $errorData = [];
        collect($collection)->map(function ($items) use (&$newCollection, &$errorData) {
            unset($items[0]);
            $items->map(function ($item) use (&$newCollection) {
                //暂时随机生成
                $newCollection->push([
                    'real_name' => $item[0],
                    'mobile' => strval($item[2]),
                    'sex' => round(0, 1),
                    'section' => round(0, 4),
                    'grade_id' => mt_rand(1, 10),
                    'class_id' => mt_rand(1, 10),
                    'account' => mt_rand(100002, 29992332),
                    'birthday' => strval($item[8]),
                ]);
            });
        });

        return $newCollection;
    }
}
/**
 * 上传学生excel
 */
if (!function_exists('uploadExcel')) {
    function uploadExcel($newFileName)
    {
        ini_set('memory_limit', '2048M');
        $path = storage_path('app/public') . '/' . $newFileName;
        $collections = Excel::toCollection(new \App\Models\ImportBaseModel(), $path)->getIterator();
        //验证数据行规则
        foreach ($collections as $collection) {
            unset($collection[0]);
            foreach ($collection as $key => $items) {
                unset($items[7], $items[8]);
                if (count(array_filter($items->toarray())) != count($items)) {
                    return output(0, "约{$key}行有空值", null);
                }
            }
            //每个字段规则需要补充
        }

        return collect($collections);
    }
}
/**
 * 过滤下空格输入
 */
if (!function_exists('space')) {
    function space($value)
    {
        $str = str_replace(["\r\n", "\r", "\n", "\t", "  ", "'", '"', "' ", '" ', ' "', " '"], " ", $value);
        return str_replace(' ', '', trim($str));
    }
}
/**
 * 获取百分比   $dividend被除数    divisor除数
 */
if (!function_exists('valuePercentage')) {
    function valuePercentage($dividend, $divisor)
    {
        $number = "0.00";
        if (empty($divisor)) {
            return $number;
        }
        $number = $dividend / $divisor * 100;
        return number_format($number, 2);
    }
}
if (!function_exists('valuePercentageV2')) {
    function valuePercentageV2($dividend, $divisor)
    {
        $number = "0.00";
        if (empty($divisor)) {
            return $number;
        }
        $number = $dividend / $divisor * 100;

        return sprintf("%.2f",substr(sprintf("%.3f", $number), 0, -1));
    }
}

/**
 *  登录用的加密token
 */
if (!function_exists('getToken')) {
    function getToken($uid, $mobile)
    {
        return md5($uid . md5($mobile . 'login2017wenda'));
    }
}


/**
 * 设置cookie
 */
if (!function_exists('setUserCookie')) {
    function setUserCookie($data)
    {
        if (!is_array($data)) {
            return false;
        }
        foreach ($data as $key => $item) {
            $item = \App\Services\Encryption::encodeStr($item);//进行加密
            \Illuminate\Support\Facades\Cookie::queue(
                $key,
                $item,
                time() + 60 * 60 * 24 * 30,//有限期30天
                '/',
                env('COOKIE_DOMAIN')
            );
//            setCookie($key,$item,  time() + 60 * 60 * 24 * 30,'/','.xinzhi.com');
        }
    }
}
/**
 * 导出excel信息
 */
if (!function_exists('exportExcelInfo')) {
    function exportExcelInfo($title, $data, $fileName = 'xxxx.xlsx')
    {

//        $data = [
//            [1, 'jack', 10],
//            [2, 'mike', 12],
//            [3, 'jane', 21],
//            [4, 'paul', 26],
//            [5, 'kitty', 25],
//            [6, 'yami', 60],
//        ];
//
//        $title = ['编号', '姓名', '年龄'];

        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        //设置工作表标题名称
        $worksheet->setTitle('工作表格');

        //表头
        //设置单元格内容
        foreach ($title as $key => $value) {
            $worksheet->setCellValueByColumnAndRow($key + 1, 1, $value);
        }

        $row = 2; //从第二行开始
        foreach ($data as $item) {
            $column = 1;

            foreach ($item as $value) {
                $worksheet->setCellValueByColumnAndRow($column, $row, $value);
                $column++;
            }
            $row++;
        }
        //2.输出到浏览器
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx'); //按照指定格式生成Excel文件

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $writer->save('php://output');
        //释放
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);

    }

}
/**
 * 递归构建树形菜单
 *
 * @param array $nodes
 * @param int $parentId
 * @param string $parentString
 * @param string $childrenString
 *
 * @return array
 */
if (!function_exists('build_nested_array')) {
    function build_nested_array(array $nodes = [], $parentId = 0, $parentString = 'parent_id', $childrenString = 'children')
    {
        $branch = [];
        foreach ($nodes as $k => $node) {
            if (empty($node->id)) {
                continue;
            }
            if ($node->$parentString == $parentId) {
                $children = build_nested_array($nodes, $node->id, $parentString, $childrenString);
                if ($children) {
                    $node->$childrenString = $children;
                }
                $branch[] = $node;
            }
        }
        return $branch;
    }
}
/**
 * pdf
 */
if (!function_exists('downloadPdf')) {
    function downloadPdf($url, $fileName = 'system.pdf')
    {
        $snappy = new \Knp\Snappy\Pdf('/usr/local/bin/wkhtmltopdf');
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        echo $snappy->getOutput($url);
    }
}


/**
 * 复检团体pdf
 */
if (!function_exists('downloadRecheckGroupPdf')) {
    function downloadRecheckGroupPdf($url, $fileName = 'system.pdf', $token = "")
    {
        $snappy = new \Knp\Snappy\Pdf('/usr/local/bin/wkhtmltopdf');
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        $options = [
            'margin-left' => '10mm',
            'margin-right' => '10mm',
            'margin-bottom' => '15mm',
            'margin-top' => '15mm',
            'page-height' => '297mm',
            'page-width' => '210mm',
            'footer-center' => '[page]',
            'page-size' => 'A4',
            'print-media-type' => true,
        ];
        echo $snappy->getOutput($url, $options);
    }
}


/**
 * 学校版本pdf
 */
if (!function_exists('downloadSchoolPdf')) {
    function downloadSchoolPdf($url, $fileName = 'system.pdf', $reportId, $token = "",$DbConnect="")
    {
        $snappy = new \Knp\Snappy\Pdf('/usr/local/bin/wkhtmltopdf');
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        $content = file_get_contents(config('main.operate_url') . '/api/report/getDownLoadRecommendCoverSchoolReportView?report_id=' . $reportId . "&token=" . $token."&DbConnect=" . $DbConnect);
        $options = [
            'margin-left' => '10mm',
            'margin-right' => '10mm',
            'margin-bottom' => '15mm',
            'margin-top' => '15mm',
            'page-height' => '297mm',
            'page-width' => '210mm',
            'cover' => $content,
            'footer-center' => '[page]',
            'page-offset' => -2,
            'page-size' => 'A4',
            'print-media-type' => true,
        ];
        echo $snappy->getOutput($url, $options);
    }
}

/**
 * 学校版本pdf
 */
if (!function_exists('downloadRecheckSchoolPdf')) {
    function downloadRecheckSchoolPdf($url, $fileName = 'system.pdf', $reportId, $token = "",$semesterStartTime="")
    {
        $snappy = new \Knp\Snappy\Pdf('/usr/local/bin/wkhtmltopdf');
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');
        $content = file_get_contents(config('main.operate_url') . '/api/report/recheck/getDownLoadRecommendCoverSchoolReportView?report_id=' . $reportId . "&token=" . $token. "&semester_start_time=" . $semesterStartTime);
        $options = [
            'margin-left' => '10mm',
            'margin-right' => '10mm',
            'margin-bottom' => '15mm',
            'margin-top' => '15mm',
            'page-height' => '297mm',
            'page-width' => '210mm',
            'cover' => $content,
            'footer-center' => '[page]',
            'page-offset' => -2,
            'page-size' => 'A4',
            'print-media-type' => true,
        ];
        echo $snappy->getOutput($url, $options);
    }
}
/**
 * 年级版本pdf
 */
if (!function_exists('downloadGradePdf')) {
    function downloadGradePdf($url, $fileName = 'system.pdf', $reportId, $token = "", $questionnaireId = 0,$semesterStartTime="")
    {
        $snappy = new \Knp\Snappy\Pdf('/usr/local/bin/wkhtmltopdf');
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');


        if (!empty($questionnaireId) && in_array($questionnaireId, config('report_common')['primary_sid_cdch'])) {
            $options = [
                'margin-left' => '10mm',
                'margin-right' => '10mm',
                'margin-bottom' => '15mm',
                'margin-top' => '15mm',
                'page-height' => '297mm',
                'page-width' => '210mm',
//                'cover' => $content,
                'footer-center' => '[page]',
//                'page-offset' => -2,
                'page-size' => 'A4',
                'print-media-type' => true,
            ];
            echo $snappy->getOutput($url, $options);
        } else {
            $content = file_get_contents(config('main.operate_url') . '/api/report/getRecommendIndividualGradeReportCover?report_id=' . $reportId . "&token=" . $token."&semester_start_time=".$semesterStartTime);

            $options = [
                'margin-left' => '10mm',
                'margin-right' => '10mm',
                'margin-bottom' => '15mm',
                'margin-top' => '15mm',
                'page-height' => '297mm',
                'page-width' => '210mm',
                'cover' => $content,
                'footer-center' => '[page]',
                'page-offset' => -2,
                'page-size' => 'A4',
                'print-media-type' => true,
            ];
            echo $snappy->getOutput($url, $options);
        }


    }
}

/**
 * 年级版本pdf
 */
if (!function_exists('downloadGradePdfZip')) {
    function downloadGradePdfZip($url, $fileName = 'system.pdf', $reportId, $token = "", $questionnaireId = 0,$semesterStartTime="")
    {
        $snappy = new \Knp\Snappy\Pdf('/usr/local/bin/wkhtmltopdf');
        header('Content-Type: application/pdf');
//        header('Content-Disposition: attachment; filename="' . $fileName . '"');


        if (!empty($questionnaireId) && in_array($questionnaireId, config('report_common')['primary_sid_cdch'])) {
            $options = [
                'margin-left' => '10mm',
                'margin-right' => '10mm',
                'margin-bottom' => '15mm',
                'margin-top' => '15mm',
                'page-height' => '297mm',
                'page-width' => '210mm',
//                'cover' => $content,
                'footer-center' => '[page]',
//                'page-offset' => -2,
                'page-size' => 'A4',
                'print-media-type' => true,
            ];
            echo $snappy->getOutput($url, $options);
        } else {
            $content = file_get_contents(config('main.operate_url') . '/api/report/getRecommendIndividualGradeReportCover?report_id=' . $reportId . "&token=" . $token."&semester_start_time=".$semesterStartTime);

            $options = [
                'margin-left' => '10mm',
                'margin-right' => '10mm',
                'margin-bottom' => '15mm',
                'margin-top' => '15mm',
                'page-height' => '297mm',
                'page-width' => '210mm',
                'cover' => $content,
                'footer-center' => '[page]',
                'page-offset' => -2,
                'page-size' => 'A4',
                'print-media-type' => true,
            ];
            echo $snappy->getOutput($url, $options);
        }


    }
}


/**
 * 年级版本pdf
 */
if (!function_exists('downloadGradeRecheckPdf')) {
    function downloadGradeRecheckPdf($url, $fileName = 'system.pdf', $reportId, $token = "", $questionnaireId = 0,$semesterStartTime="")
    {
        $snappy = new \Knp\Snappy\Pdf('/usr/local/bin/wkhtmltopdf');
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');




            $content = file_get_contents(config('main.operate_url') . '/api/report/recheck/getRecommendIndividualGradeReportCover?report_id=' . $reportId . "&token=" . $token ."&semester_start_time=" . $semesterStartTime);

            $options = [
                'margin-left' => '10mm',
                'margin-right' => '10mm',
                'margin-bottom' => '15mm',
                'margin-top' => '15mm',
                'page-height' => '297mm',
                'page-width' => '210mm',
                'cover' => $content,
                'footer-center' => '[page]',
                'page-offset' => -2,
                'page-size' => 'A4',
                'print-media-type' => true,
            ];
            echo $snappy->getOutput($url, $options);


    }
}

/**
 * 年级版本pdf
 */
if (!function_exists('downloadGradeRecheckPdfZip')) {
    function downloadGradeRecheckPdfZip($url, $fileName = 'system.pdf', $reportId, $token = "", $questionnaireId = 0,$semesterStartTime="")
    {
        $snappy = new \Knp\Snappy\Pdf('/usr/local/bin/wkhtmltopdf');
        header('Content-Type: application/pdf');
//        header('Content-Disposition: attachment; filename="' . $fileName . '"');




        $content = file_get_contents(config('main.operate_url') . '/api/report/recheck/getRecommendIndividualGradeReportCover?report_id=' . $reportId . "&token=" . $token ."&semester_start_time=" . $semesterStartTime);

        $options = [
            'margin-left' => '10mm',
            'margin-right' => '10mm',
            'margin-bottom' => '15mm',
            'margin-top' => '15mm',
            'page-height' => '297mm',
            'page-width' => '210mm',
            'cover' => $content,
            'footer-center' => '[page]',
            'page-offset' => -2,
            'page-size' => 'A4',
            'print-media-type' => true,
        ];
        echo $snappy->getOutput($url, $options);


    }
}
/**
 * 班级版本pdf
 */
if (!function_exists('downloadClassPdf')) {
    function downloadClassPdf($url, $fileName = 'system.pdf', $reportId, $token = "",$DbConnect="")
    {
        $snappy = new \Knp\Snappy\Pdf('/usr/local/bin/wkhtmltopdf');
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');


        $content = file_get_contents(config('main.operate_url') . '/api/report/getRecommendIndividualClassReportCover?report_id=' . $reportId . "&token=" . $token."&DbConnect=" .$DbConnect);

        $options = [
            'margin-left' => '10mm',
            'margin-right' => '10mm',
            'margin-bottom' => '15mm',
            'margin-top' => '15mm',
            'page-height' => '297mm',
            'page-width' => '210mm',
            'cover' => $content,
            'footer-center' => '[page]',
            'page-offset' => -2,
            'page-size' => 'A4',
            'print-media-type' => true,
        ];
        echo $snappy->getOutput($url, $options);
    }
}



/**
 * 班级版本pdf
 */
if (!function_exists('downloadClassRecheckPdf')) {
    function downloadClassRecheckPdf($url, $fileName = 'system.pdf', $reportId, $token = "",$semesterStartTime="")
    {
        $snappy = new \Knp\Snappy\Pdf('/usr/local/bin/wkhtmltopdf');
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');


        $content = file_get_contents(config('main.operate_url') . '/api/report/recheck/getRecommendIndividualClassReportCover?report_id=' . $reportId . "&token=" . $token. "&semester_start_time=" . $semesterStartTime);

        $options = [
            'margin-left' => '10mm',
            'margin-right' => '10mm',
            'margin-bottom' => '15mm',
            'margin-top' => '15mm',
            'page-height' => '297mm',
            'page-width' => '210mm',
            'cover' => $content,
            'footer-center' => '[page]',
            'page-offset' => -2,
            'page-size' => 'A4',
            'print-media-type' => true,
        ];
        echo $snappy->getOutput($url, $options);
    }
}


/**
 * 班级版本pdf
 */
if (!function_exists('downloadClassRecheckPdfZip')) {
    function downloadClassRecheckPdfZip($url, $fileName = 'system.pdf', $reportId, $token = "",$semesterStartTime="")
    {
        $snappy = new \Knp\Snappy\Pdf('/usr/local/bin/wkhtmltopdf');
        header('Content-Type: application/pdf');
//        header('Content-Disposition: attachment; filename="' . $fileName . '"');


        $content = file_get_contents(config('main.operate_url') . '/api/report/recheck/getRecommendIndividualClassReportCover?report_id=' . $reportId . "&token=" . $token. "&semester_start_time=" . $semesterStartTime);

        $options = [
            'margin-left' => '10mm',
            'margin-right' => '10mm',
            'margin-bottom' => '15mm',
            'margin-top' => '15mm',
            'page-height' => '297mm',
            'page-width' => '210mm',
            'cover' => $content,
            'footer-center' => '[page]',
            'page-offset' => -2,
            'page-size' => 'A4',
            'print-media-type' => true,
        ];
        echo $snappy->getOutput($url, $options);
    }
}
/**
 * 班级版本pdf
 */
if (!function_exists('downloadClassChengHuaPdf')) {
    function downloadClassChengHuaPdf($url, $fileName = 'system.pdf', $reportId, $token = "")
    {
        $snappy = new \Knp\Snappy\Pdf('/usr/local/bin/wkhtmltopdf');
        header('Content-Type: application/pdf');
        header('Content-Disposition: attachment; filename="' . $fileName . '"');



        $options = [
            'margin-left' => '10mm',
            'margin-right' => '10mm',
            'margin-bottom' => '15mm',
            'margin-top' => '15mm',
            'page-height' => '297mm',
            'page-width' => '210mm',
            'footer-center' => '[page]',
            'page-offset' => -2,
            'page-size' => 'A4',
            'print-media-type' => true,
        ];
        echo $snappy->getOutput($url, $options);
    }
}


if (!function_exists('isMunicipalities')) {
    /**
     * 是否是直辖市
     *
     * @param $province
     *
     * @return bool
     */
    function isMunicipalities($province = '')
    {
        if (in_array($province, [110000, 120000, 310000, 500000])) {
            return true;
        }
        return false;
    }

}


if (!function_exists('queryPlan')) {
    /**
     * @param $buildQuery
     * @param $planId
     * @return mixed
     */
    function queryPlanComplete($buildQuery, $planId)
    {
        $buildQuery->join('lime_distribution_questionnaire as ldq', 'ldq.batch', '=', 'lep.plan_uuid')
            ->join('lime_user_info as lui', 'lui.uid', '=', 'ldq.uid')
            ->join('lime_school_grade as lsg', 'lsg.id', '=', 'lui.grade_id')
            ->leftjoin('lime_user_questionnaire as luq', 'luq.dq_id', '=', 'ldq.id')
            ->where('luq.is_finish', '=', 1) //完成的
            ->where('lep.id', '=', $planId);

        return $buildQuery;
    }

}


if (!function_exists('sumSource')) {
    function sumScoreAvg($sum, $score)
    {
        if (empty($score)) {
            return "";
        }
        $avg = $sum / $score;
        return number_format($avg, 2);
    }
}


/**
 * 生成账号
 */
if (!function_exists('makeCodeNumber')) {
    function makeCodeNumber()
    {
        return str_pad(mt_rand(1, 9999999999), 10, '0', STR_PAD_LEFT);
    }
}

/**
 * 比例对比
 */
if (!function_exists('compare')) {
    function compare($param, $object)
    {
        //第四段男女比较比例
        if ($param > $object) {
            return '高于';
        } elseif ($param < $object) {
            return '低于';
        } else {
            return '等于';
        }
    }
}

/**
 * 获取手机号
 * @param $mobile
 * @return integer
 */
if (!function_exists('getPhoneNumber')) {
    function getPhoneNumber($mobile)
    {
        $mobile = \App\Libs\Encryption::getLoginToken($mobile);
        $encryptionMobile = '';
        if (!empty($mobile)) {
            $encryptionMobile = substr_replace($mobile[0], '****', 3, 4);
        }
        return $encryptionMobile;
    }
}


if (!function_exists('trimComma')) {
    //移除末尾字符
    function trimComma($string)
    {
        return rtrim($string, "、");
    }
}


if (!function_exists('numberFormat')) {
    function numberFormat($number)
    {
        if (empty($number)) {
            return "0.00";
        }
        return number_format($number, 2);
    }
}



if (!function_exists('numberFormatT')) {
    function numberFormatT($number)
    {
        if (empty($number)) {
            return "0.00";
        }
        return number_format($number*100, 2);
    }
}


if (!function_exists('fmtPrintln')) {
    /**
     * 输出
     * @param $param
     * @return void
     */
    function fmtPrintln($param)
    {
        return dd($param);
    }
}



/**
 * 移除末尾逗号
 */
if (!function_exists('trimUnset')) {
    //移除末尾字符
    function trimUnset($string)
    {
        return rtrim($string, "，");
    }
}


/**
 * 替换
 */
if (!function_exists('replace')) {
    function replace($value)
    {
        return space(str_replace(array("\r\n", "\r", "\n", "\t", "", "*", "XX"), "", $value));
    }
}


/**
 * 验证字符 0.00
 */
if (!function_exists('isNil')) {
    function isNil($number)
    {
        if ($number == '0.00') {
            return true;
        }
        return false;
    }
}


//获取年级
if (!function_exists('getGradeCodeName')) {
    function getGradeCodeName($two = true, $date = '')
    {
        $grade = [
            27 => ['id' => 1, 'name' => '一年级'], 26 => ['id' => 2, 'name' => '二年级'], 25 => ['id' => 3, 'name' => '三年级'],                                                  //小学
            24 => ['id' => 4, 'name' => '四年级'], 23 => ['id' => 5, 'name' => '五年级'], 22 => ['id' => 6, 'name' => '六年级'],                                                    //小学
            205 => ['id' => 7, 'name' => '七年级'], 204 => ['id' => 8, 'name' => '八年级'], 203 => ['id' => 9, 'name' => '九年级'],                                                    //初中
            404 => ['id' => 10, 'name' => '高一'], 403 => ['id' => 11, 'name' => '高二'], 402 => ['id' => 12, 'name' => '高三'],                                                       //高中
            //503 => ['id' => 13, 'name' => '大一'],502 => ['id' => 14, 'name' => '大二'],501 => ['id' => 15, 'name' => '大三'],500 => ['id' => 16, 'name' => '大四']                //大学
        ];
        $result = [];
        $startYear = 2018;
        $curTime = $date ? strtotime($date) : time();
        $curYear = date('Y', $curTime);
        if ($curYear - $startYear > 0) {
            $september = strtotime($curYear . '-09-01');
            if ($curTime >= $september) {
                foreach ($grade as $key => $val) {
                    $result[$key + $curYear - $startYear] = $val;
                }
            } else {
                foreach ($grade as $key => $val) {
                    $result[$key + $curYear - $startYear - 1] = $val;
                }
            }
        } else {
            $result = $grade;
        }
        switch ($two) {
            case true :
                return $result + [
                        //1  => ['id' => 1, 'name' => '一年级'],2  => ['id' => 2, 'name' => '二年级'],3  => ['id' => 3, 'name' => '三年级'],                                                     //小学
                        4 => ['id' => 4, 'name' => '四年级'], 5 => ['id' => 5, 'name' => '五年级'], 6 => ['id' => 6, 'name' => '六年级'],                                                    //小学
                        7 => ['id' => 7, 'name' => '七年级'], 8 => ['id' => 8, 'name' => '八年级'], 9 => ['id' => 9, 'name' => '九年级'],                                                    //初中
                        10 => ['id' => 10, 'name' => '高一'], 11 => ['id' => 11, 'name' => '高二'], 12 => ['id' => 12, 'name' => '高三'],                                                      //高中
                        //13 => ['id' => 13, 'name' => '大一'],14 => ['id' => 14, 'name' => '大二'],15 => ['id' => 15, 'name' => '大三'],16 => ['id' => 16, 'name' => '大四']                   //大学
                    ];
            default :
                return $result;
        }
    }

    /**
     *
     */
    if (!function_exists('reviewExecute')) {
        function reviewExecute($info)
        {
            Blogger::getLogger('review_school_report_execute_success')->info("============报告执行-成功==============：", ['result' =>$info]);
        }
    }



    if (!function_exists('numberFormatPer')) {
        function numberFormatPer($dividend, $divisor)
        {
            if (empty($divisor)) {
                return '0.00';
            }
            $number = $dividend / $divisor * 100;
            return number_format($number, 2);
        }
    }


    if (!function_exists('emptyFormat')) {
        function emptyFormat($param)
        {
            if (empty($param)  || $param=="0.00") {
                return true;
            }
            return false;
        }
    }



    if (!function_exists('scaleStatus')) {
        function scaleStatus($scaleId)
        {
           if (in_array($scaleId,[115,116,117,118,119,120,121,122,123,112,113])){
               return 1;
           }
           return 0;
        }
    }



    /**
     * 请求接口
     */
    if (!function_exists('makeClientRequest')) {
        function makeClientRequest($options, $url, $method)
        {
            $client = new \GuzzleHttp\Client();
            try {
                $response = $client->request($method, $url, ['query' => $options]);
                $result = [];
                if ($response->getStatusCode() == 200) {
                    $response = $response->getBody()->getContents();
                    $result = json_decode($response)->data;
                }
                return $result;
            } catch (\GuzzleHttp\Exception\RequestException $e) {
                return [];
            }
        }
    }

    /**
     * 请求接口
     */
    if (!function_exists('makeClientRequestFaculty')) {
        function makeClientRequestFaculty($options, $url, $method)
        {
            $client = new \GuzzleHttp\Client();
            try {
                $response = $client->request($method, $url, ['query' => $options]);
                $result = [];
                if ($response->getStatusCode() == 200) {
                    $response = $response->getBody()->getContents();
                    $result = json_decode($response, true);
                    if ($result['code']) {
                        $result = $result['data'];
                    } else {
                        $result = [];
                    }
                }
                return $result;
            } catch (\GuzzleHttp\Exception\RequestException $e) {
                return [];
            }
        }
    }


    /**
     * 小o
     * 发送json数据
     */
    if (!function_exists('makeClientJsonRequest')) {
        function makeClientJsonRequest($options, $url, $method)
        {
            $client = new \GuzzleHttp\Client();
            try {
                Blogger::getLogger('school-report-from')->info("学校报告生成请求参数：" . json_encode($options));
                $response = $client->request($method, $url, ['json' => $options]);
                $result = [];
                if ($response->getStatusCode() == 200) {
                    $response = $response->getBody()->getContents();
                    Blogger::getLogger('school-report-from')->info("学校报告生成请求成功：" . json_encode($response));
                    $result = json_decode($response)->status;
                }
                return $result;
            } catch (\GuzzleHttp\Exception\RequestException $e) {
                return [];
            }
        }
    }
}


/**
 * 解密
 */
if (!function_exists('UmsDecrypt')) {
    function UmsDecrypt($param, $secretKey)
    {
        $param = urldecode($param);
        $param = openssl_decrypt($param, 'AES-128-ECB', $secretKey);
        if (!$param) {
            return false;
        }
        return $param;
    }
}


/**
 * 统一加密
 */
if (!function_exists('UmsEncrypt')) {
    function UmsEncrypt($param, $secretKey)
    {
        if (!is_array($param) || empty($param)) {
            return false;
        }
        $param = json_encode($param, JSON_UNESCAPED_UNICODE);
        $data = openssl_encrypt($param, 'AES-128-ECB', $secretKey);
        return urlencode($data);
    }
}


/**
 * 请求验证接口
 */
if (!function_exists('verifyJavaToken')) {
    function verifyJavaToken($options, $url, $method, $authInfo)
    {
        $client = new \GuzzleHttp\Client();
        try {
            $response = $client->request($method, $url, [
                'query' => $options,
                'headers' => [
                    'token' => "Bearer {$authInfo->token}"
                ]
            ]);
            if (in_array($response->getStatusCode(), [200, 401])) {
                return \GuzzleHttp\json_decode($response->getBody()->getContents());
            }
            Blogger::getLogger("Request-Java-verify-token")->info("验证token失败-");
            return false;
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            Blogger::getLogger("Request-Java-verify-token")->info("验证token异常-" . $e->getMessage());
            return false;
        }
    }
}


/**
 * 模拟接口数据
 */
if (!function_exists('checkJavaToken')) {
    function checkJavaFromData($options, $url, $method)
    {
        $client = new \GuzzleHttp\Client();
        try {
            $response = $client->request($method, $url, [
                'query' => $options,
            ]);
            if (in_array($response->getStatusCode(), [200, 401])) {
                return \GuzzleHttp\json_decode($response->getBody()->getContents());
            }
            return false;
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            return false;
        }
    }
}

/**
 * 登录请求不需要token
 * @package
 */
if (!function_exists('loginClientRequest')) {
    function loginClientRequest($options, $url, $method)
    {
        $client = new \GuzzleHttp\Client();
        try {
            $response = $client->request($method, $url, [
                'json' => $options,
            ]);
            if ($response->getStatusCode() == 200) {
                return \GuzzleHttp\json_decode($response->getBody()->getContents());
            }
            return false;
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            return false;
        }
    }
}


/**
 * 同步信息使用
 * @package
 */
if (!function_exists('batchClientRequest')) {
    function batchClientRequest($options, $url, $method)
    {
        $client = new \GuzzleHttp\Client();
        try {
            $response = $client->request($method, $url, [
                'json' => $options,
            ]);
            if ($response->getStatusCode() == 200) {
                return \GuzzleHttp\json_decode($response->getBody()->getContents());
            }
            Blogger::getLogger("batch-member-sync-ums-info-error-info")->info("系统平台接口:system/user/synchroBatchUser ---同步失败：" . json_encode($response->getBody()->getContents()));
            return false;
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            Blogger::getLogger("batch-member-sync-ums-info-error-info")->info("系统平台接口:system/user/synchroBatchUser ---同步失败：" . json_encode($e->getMessage()));
            return false;
        }
    }
}


/**
 * 模拟接口数据
 */
if (!function_exists('checkJavaFromDataQuery')) {
    function checkJavaFromDataQuery($options, $url, $method)
    {
        $client = new \GuzzleHttp\Client();
        $authToken = userInfo()->auth_token;
        try {
            $response = $client->request($method, $url, [
                'query' => $options,
                'timeout' => 5,
                'headers' => [
                    'token' => "Bearer $authToken"
                ]
            ]);
            if ($response->getStatusCode() == 200) {
                return \GuzzleHttp\json_decode($response->getBody()->getContents());
            }
            return false;
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            return false;
        }
    }
}


/**
 * 请求数据需携带对方token
 * @package
 */
if (!function_exists('javaClientRequest')) {
    function javaClientRequestV1($options, $url, $method)
    {
        $client = new \GuzzleHttp\Client();
        if (!isset(userInfo()->auth_token)){
            $authToken = "";
        }else{
            $authToken = userInfo()->auth_token;
        }

        try {
            $response = $client->request($method, $url, [
                'json' => $options,
                'timeout' => 5,
                'headers' => [
                    'token' => "Bearer $authToken"
                ]
            ]);
            if ($response->getStatusCode() == 200) {
                return \GuzzleHttp\json_decode($response->getBody()->getContents());
            }
            return false;
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            return false;
        }
    }
}


if (!function_exists('javaClientComRequest')) {
    function javaClientComRequest($options, $url, $method)
    {
        $client = new \GuzzleHttp\Client();
        $authToken = config("systems.token_ums");
        try {
            $response = $client->request($method, $url, [
                'json' => $options,
                'timeout' => 5,
                'headers' => [
                    'token' => "Bearer $authToken"
                ]
            ]);
            if ($response->getStatusCode() == 200) {
                return \GuzzleHttp\json_decode($response->getBody()->getContents());
            }
            return false;
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            return false;
        }
    }
}


/**
 * 请求数据需携带对方token
 * @package
 */
if (!function_exists('javaClientRequest')) {
    function javaClientRequest($options, $url, $method)
    {
        $client = new \GuzzleHttp\Client();
        $authToken = userInfo()->auth_token;
        try {
            $response = $client->request($method, $url, [
                'json' => $options,
                'timeout' => 5,
                'headers' => [
                    'token' => "Bearer $authToken"
                ]
            ]);
            if ($response->getStatusCode() == 200) {
                return \GuzzleHttp\json_decode($response->getBody()->getContents());
            }
            return false;
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            return false;
        }
    }
}


if (!function_exists('queryPowerAreaModel')) {
    /**
     * 返回对象model区域权限
     * @param $buildQuery
     * @param $alias
     * @param $searchInput
     * @return mixed
     */
    function queryPowerAreaModel($buildQuery, $alias, $searchInput)
    {
        //区域权限查询
        if ($searchInput['power'] != 1) {
            $buildQuery = $buildQuery->whereIn($alias . '.province', $searchInput['region_list']['province']);
            if (in_array($searchInput['power'], [3, 4, 5])) {
                $buildQuery = $buildQuery->whereIn($alias . '.city', $searchInput['region_list']['city']);
            }
            if (in_array($searchInput['power'], [4, 5])) {
                $buildQuery = $buildQuery->whereIn($alias . '.area', $searchInput['region_list']['area']);
            }
            if (in_array($searchInput['power'], [5])) {
                if ($alias == "los") {
                    $buildQuery = $buildQuery->whereIn($alias . '.school_id', $searchInput['region_list']['school_id']);
                } else {
                    $buildQuery = $buildQuery->whereIn($alias . '.id', $searchInput['region_list']['school_id']);
                }
            }
        }
        return $buildQuery;
    }
}

/**
 * 请求数据需携带对方token
 * @package
 */
if (!function_exists('delJavaClientRequest')) {
    function delJavaClientRequest($options, $url, $method)
    {
        $client = new \GuzzleHttp\Client();
        $authToken = "";
        try {
            $response = $client->request($method, $url, [
                'json' => $options,
                'timeout' => 5,
                'headers' => [
                    'token' => "Bearer $authToken"
                ]
            ]);
            if ($response->getStatusCode() == 200) {
                return \GuzzleHttp\json_decode($response->getBody()->getContents());
            }
            return false;
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            return false;
        }
    }
}

if (!function_exists('queryPowerUserAreaModel')) {
    /**
     * 返回对象model区域权限
     * @param $buildQuery
     * @param $alias
     * @param $searchInput
     * @return mixed
     */
    function queryPowerUserAreaModel($buildQuery, $alias, $searchInput)
    {
        //用户列表身份
        if ($searchInput['power'] != 1) {
            $buildQuery = $buildQuery->whereIn($alias . '.province', $searchInput['region_list']['province']);
            if (in_array($searchInput['power'], [3, 4, 5, 6, 7, 8])) {
                $buildQuery = $buildQuery->whereIn($alias . '.city', $searchInput['region_list']['city']);
            }
            if (in_array($searchInput['power'], [4, 5, 6, 7, 8])) {
                $buildQuery = $buildQuery->whereIn($alias . '.area', $searchInput['region_list']['area']);
            }
            if (in_array($searchInput['power'], [5, 6, 7, 8])) {
                if (in_array($alias, ['los', 'surr'])) {
                    $buildQuery = $buildQuery->whereIn($alias . '.school_id', $searchInput['region_list']['school_id']);
                } else {
                    $buildQuery = $buildQuery->whereIn($alias . '.id', $searchInput['region_list']['school_id']);
                }
            }
            //用户所属区域
            if (in_array($searchInput['power'], [6, 7, 8])) {
                $buildQuery = $buildQuery->whereIn($alias . '.section_id', $searchInput['region_list']['section_id']);
            }
            if (in_array($searchInput['power'], [7, 8])) {
                $buildQuery = $buildQuery->whereIn($alias . 'grade_id', $searchInput['region_list']['grade_id']);
            }
            if (in_array($searchInput['power'], [8])) {
                $buildQuery = $buildQuery->whereIn($alias . '.class_id', $searchInput['region_list']['class_id']);
            }
        }
        return $buildQuery;
    }
}


if (!function_exists('checkPowerAreaPermission')) {
    /**
     * 检测区域操作权限
     * @param $informationInfo
     * @param $powerInfo
     * @return bool
     */
    function checkPowerAreaPermission($informationInfo, $powerInfo)
    {
        switch ($powerInfo['power']) {
            case 8;
            case 7;
            case 6;
            case 5:
                if (!in_array($informationInfo->school_id, $powerInfo['region_list']['school_id'])) {
                    throw new \RuntimeException("暂无权限操作");
                }
                break;
            case 4:
                if (!in_array($informationInfo->area, $powerInfo['region_list']['area'])) {
                    throw new \RuntimeException("暂无权限操作");
                }
                break;
            case 3:
                if (!in_array($informationInfo->city, $powerInfo['region_list']['city'])) {
                    throw new \RuntimeException("暂无权限操作");
                }
                break;
            case 2:
                if (!in_array($informationInfo->province, $powerInfo['region_list']['province'])) {
                    throw new \RuntimeException("暂无权限操作");
                }
                break;
            case 1:
            default:
        }
        return true;
    }


    /**
     * pdf
     */
    if (!function_exists('downloadPdfZip')) {
        function downloadPdfZip($url, $fileName = 'system.pdf')
        {
            $snappy = new \Knp\Snappy\Pdf('/usr/local/bin/wkhtmltopdf');
            header('Content-Type: application/pdf');
//        header('Content-Disposition: attachment; filename="' . $fileName . '"');
            echo $snappy->getOutput($url);
        }
    }

}

if (!function_exists('getPermissionAreaFilterModel')) {
    /**
     * 返回对象model区域权限
     * @param $buildQuery
     * @param $alias
     * @param $searchInput
     * @return mixed
     */
    function getPermissionAreaFilterModel($buildQuery, $alias, $sectionAlias, $gradeAlias, $classAlias, $searchInput)
    {
        //区域权限查询
        if ($searchInput['power'] != 1) {
            $buildQuery = $buildQuery->whereIn($alias . '.province', $searchInput['region_list']['province']);
            if (in_array($searchInput['power'], [3, 4, 5, 6, 7, 8])) {
                $buildQuery = $buildQuery->whereIn($alias . '.city', $searchInput['region_list']['city']);
            }
            if (in_array($searchInput['power'], [4, 5, 6, 7, 8])) {
                $buildQuery = $buildQuery->whereIn($alias . '.area', $searchInput['region_list']['area']);
            }
            if (in_array($searchInput['power'], [5, 6, 7, 8])) {
                if ($alias == "los") {
                    $buildQuery = $buildQuery->whereIn($alias . '.school_id', $searchInput['region_list']['school_id']);
                } else {
                    $buildQuery = $buildQuery->whereIn($alias . '.id', $searchInput['region_list']['school_id']);
                }
            }
            if (in_array($searchInput['power'], [6, 7, 8])) {
                $buildQuery = $buildQuery->whereIn($sectionAlias . '.id', $searchInput['region_list']['section_id']);
            }
            if (in_array($searchInput['power'], [7, 8])) {
                $buildQuery = $buildQuery->whereIn($gradeAlias . '.id', $searchInput['region_list']['grade_id']);
            }
            if (in_array($searchInput['power'], [8])) {
                $buildQuery = $buildQuery->whereIn($classAlias . '.id', $searchInput['region_list']['class_id']);
            }
        }
        return $buildQuery;
    }
}


if (!function_exists('paramConversion')) {
    function paramConversion($string)
    {
        $string = preg_replace_callback('/_([a-zA-Z])/', function ($match) {
            return strtoupper($match[1]);
        }, $string);
        return false ? ucfirst($string) : $string;
    }
}


if (!function_exists('syncInfoToJmInfo')) {
    function syncInfoToJmInfo($paramInfo, $method, $localRoute, $jmRoute)
    {
        Blogger::getLogger("make-sync-user-role-menu-success")->info("接口方法:$localRoute ---需要同步系统平台的数据" . json_encode($paramInfo));
        $requestUrl = config('main.java_ums_url') . '/' . $jmRoute;
        $sysStatus = javaClientRequest($paramInfo, $requestUrl, $method);
        if (empty($sysStatus) || $sysStatus->code != 200) {
            Blogger::getLogger("make-sync-user-role-menu-error")->info("系统平台接口:$jmRoute ---同步失败：" . json_encode($sysStatus));
            throw  new \RuntimeException('同步数据失败！');
        }
    }
}


/**
 * 导出excel信息
 */
if (!function_exists('exportCsvInfo')) {
    function exportCsvInfo($title, $data, $fileName = 'xxxx.csv')
    {
        set_time_limit(0);
        $arrData = array_merge($title, $data);
        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $writer = new \PhpOffice\PhpSpreadsheet\Writer\Csv($spreadsheet);
        header('Content-Description: File Transfer');
        header('Expires: 0');
        header('Cache-Control: must-revalidate');
        header('Pragma: public');
        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename=' . $fileName);
        header('Cache-Control: max-age=0');
//        $writer->save('php://output');
        $fp = fopen('php://output', 'a');//打开output流

        collect($arrData)->chunk(100)->each(function ($item, $value) use ($fp) {
            foreach ($item as $subItem) {
                mb_convert_variables('GBK', 'UTF-8', $subItem);
                fputcsv($fp, $subItem);
            }
            if (ob_get_level() > 0) {
                ob_flush();
                flush();//必须同时使用 ob_flush() 和flush() 函数来刷新输出缓冲。
            }


        });
        fclose($fp);
        exit();
    }

    /**
     * 班级版本pdf
     */
    if (!function_exists('downloadClassPdfZip')) {
        function downloadClassPdfZip($url, $fileName = 'system.pdf', $reportId, $token = "",$DbConnect="")
        {
            $snappy = new \Knp\Snappy\Pdf('/usr/local/bin/wkhtmltopdf');
            header('Content-Type: application/pdf');
//            header('Content-Disposition: attachment; filename="' . $fileName . '"');
            $content = file_get_contents(config('main.operate_url') . '/api/report/getRecommendIndividualClassReportCover?report_id=' . $reportId . "&token=" . $token. "&DbConnect=" . $DbConnect);
            $options = [
                'margin-left' => '10mm',
                'margin-right' => '10mm',
                'margin-bottom' => '15mm',
                'margin-top' => '15mm',
                'page-height' => '297mm',
                'page-width' => '210mm',
                'cover' => $content,
                'footer-center' => '[page]',
                'page-offset' => -2,
                'page-size' => 'A4',
                'print-media-type' => true,
            ];
            echo $snappy->getOutput($url, $options);
        }
    }
}
/**
 * pdf
 */
if (!function_exists('saveReportPdf')) {
    function saveReportPdf($url, $fileName = 'system.pdf')
    {
        $snappy = new \Knp\Snappy\Pdf('/usr/local/bin/wkhtmltopdf');
//        header('Content-Type: application/pdf');
//        header('Content-Disposition: attachment; filename="' . $fileName . '"');
//        echo $snappy->getOutput($url);
        $pdfPath = "excel/individual";//存储相对路径
        $realPdfPath = public_path($pdfPath);//获取绝对路径
        $fileName = uniqid() . rand(100, 999);//pdf名称
        $realPath = '/' . date('Ymd') . '/' . $fileName . '.pdf';//真实路径
        $path = $realPdfPath . $realPath;
        $snappy->generate($url, $path);

        return ['http_path' => $pdfPath . $realPath, 'real_path' => $path];//返回路径
    }
}
/**
 * 年级版本pdf
 */
if (!function_exists('saveDownloadGradePdf')) {
    function saveDownloadGradePdf($url, $fileName = 'system.pdf', $reportId, $token = "")
    {
        $snappy = new \Knp\Snappy\Pdf('/usr/local/bin/wkhtmltopdf');

        $content = file_get_contents(config('main.operate_url') . '/api/report/getRecommendIndividualGradeReportCover?report_id=' . $reportId . "&token=" . $token);

        $options = [
            'margin-left' => '10mm',
            'margin-right' => '10mm',
            'margin-bottom' => '15mm',
            'margin-top' => '15mm',
            'page-height' => '297mm',
            'page-width' => '210mm',
            'cover' => $content,
            'footer-center' => '[page]',
            'page-offset' => -2,
            'page-size' => 'A4',
            'print-media-type' => true,
        ];

        $pdfPath = "excel/gradeReport";//存储相对路径
        $realPdfPath = public_path($pdfPath);//获取绝对路径
        $fileName = uniqid() . rand(100, 999);//pdf名称
        $realPath = '/' . date('Ymd') . '/' . $fileName . '.pdf';//真实路径
        $path = $realPdfPath . $realPath;
        $snappy->setOptions($options);
        $snappy->generate($url, $path);

        return ['http_path' => $pdfPath . $realPath, 'real_path' => $path];//返回路径
    }
}
/**
 * 请求数据需携带对方token
 * @package
 */
if (!function_exists('javaClientRequestByWord')) {
    function javaClientRequestByWord($options, $url, $method)
    {
        $client = new \GuzzleHttp\Client();
//        $authToken = userInfo()->auth_token;

        try {
            $response = $client->request($method, $url, [
//                'json' => $options,
                'timeout' => 1000,
//                'headers' => [
//                    'token' => "Bearer $authToken"
//                ]
                'form_params' => [
                    'srcPath' => $options['pdf_url'],
                    'fileName' => $options['word_name'],
//                    'other_field' => '123',
//                    'nested_field' => [
//                        'nested' => 'hello'
//                    ]
                ]
            ]);

            if ($response->getStatusCode() == 200) {
                $returnContent = $response->getBody()->getContents();
                Blogger::getLogger("java_pdf_to_word_info")->info("返回的数据", ['data' => $returnContent]);
                if (empty($returnContent)) {
                    Blogger::getLogger("java_pdf_to_word_info")->info("返回的数据为空", ['data' => $returnContent]);
                    return false;
                }
                return \GuzzleHttp\json_decode($returnContent, true);
            }
            Blogger::getLogger("java_pdf_to_word_error")->error("返回的数据", ['data' => $response->getBody()->getContents()]);
            return false;
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            Blogger::getLogger("java_pdf_to_word_error")->error("异常：" . $e->getMessage());
            return false;
        }
    }
}


/**
 * 班级版本pdf
 */
if (!function_exists('saveDownloadClassPdf')) {
    function saveDownloadClassPdf($url, $fileName = 'system.pdf', $reportId, $token = "")
    {
        $snappy = new \Knp\Snappy\Pdf('/usr/local/bin/wkhtmltopdf');

        $content = file_get_contents(config('main.operate_url') . '/api/report/getRecommendIndividualClassReportCover?report_id=' . $reportId . "&token=" . $token);

        $options = [
            'margin-left' => '10mm',
            'margin-right' => '10mm',
            'margin-bottom' => '15mm',
            'margin-top' => '15mm',
            'page-height' => '297mm',
            'page-width' => '210mm',
            'cover' => $content,
            'footer-center' => '[page]',
            'page-offset' => -2,
            'page-size' => 'A4',
            'print-media-type' => true,
        ];

        $pdfPath = "excel/classReport";//存储相对路径
        $realPdfPath = public_path($pdfPath);//获取绝对路径
        $fileName = uniqid() . rand(100, 999);//pdf名称
        $realPath = '/' . date('Ymd') . '/' . $fileName . '.pdf';//真实路径
        $path = $realPdfPath . $realPath;
        $snappy->setOptions($options);
        $snappy->generate($url, $path);

        return ['http_path' => $pdfPath . $realPath, 'real_path' => $path];//返回路径
    }
}


/**
 * 学校新版本pdf
 */
if (!function_exists('saveDownloadSchoolPdfByV2')) {
    function saveDownloadSchoolPdfByV2($url, $fileName = 'system.pdf', $reportId, $token = "")
    {
        $snappy = new \Knp\Snappy\Pdf('/usr/local/bin/wkhtmltopdf');
        $content = file_get_contents(config('main.operate_url') . '/api/report/getDownLoadRecommendCoverSchoolReportView?report_id=' . $reportId . "&token=" . $token);
        $options = [
            'margin-left' => '10mm',
            'margin-right' => '10mm',
            'margin-bottom' => '15mm',
            'margin-top' => '15mm',
            'page-height' => '297mm',
            'page-width' => '210mm',
            'cover' => $content,
            'footer-center' => '[page]',
            'page-offset' => -2,
            'page-size' => 'A4',
            'print-media-type' => true,
        ];

        $pdfPath = "excel/schoolReport";//存储相对路径
        $realPdfPath = public_path($pdfPath);//获取绝对路径
        $fileName = uniqid() . rand(100, 999);//pdf名称
        $realPath = '/' . date('Ymd') . '/' . $fileName . '.pdf';//真实路径
        $path = $realPdfPath . $realPath;
        $snappy->setOptions($options);
        $snappy->generate($url, $path);

        return ['http_path' => $pdfPath . $realPath, 'real_path' => $path];//返回路径
    }
}
/**
 * 文雅静
 * 发送json数据
 */
if (!function_exists('makeClientPyJsonRequest')) {
    function makeClientPyJsonRequest($options, $url, $method)
    {
        $client = new \GuzzleHttp\Client();
        try {
            $response = $client->request($method, $url, ['json' => $options]);
            $result = [];
            if ($response->getStatusCode() == 200) {
                $response = $response->getBody()->getContents();
                Blogger::getLogger('py-success')->info("请求更新成功：" . json_encode($response));
                $result = json_decode($response)->code;
            }
            return $result;
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            Blogger::getLogger('py-error')->info("请求更新失败：" . json_encode($e->getMessage()));
            return [];
        }
    }
}


/**
 * 学校pdf
 */
if (!function_exists('saveDownloadSchoolPdfByV1')) {
    function saveDownloadSchoolPdfByV1($url, $fileName = 'system.pdf', $reportId, $token = "")
    {
        $snappy = new \Knp\Snappy\Pdf('/usr/local/bin/wkhtmltopdf');
        $pdfPath = "excel/schoolReport";//存储相对路径
        $realPdfPath = public_path($pdfPath);//获取绝对路径
        $fileName = uniqid() . rand(100, 999);//pdf名称
        $realPath = '/' . date('Ymd') . '/' . $fileName . '.pdf';//真实路径
        $path = $realPdfPath . $realPath;
        $snappy->generate($url, $path);
        return ['http_path' => $pdfPath . $realPath, 'real_path' => $path];//返回路径
    }
}

/**
 * 请求接口
 */
if (!function_exists('makeClientRequestNew')) {
    function makeClientRequestNew($options, $url, $method)
    {
        $client = new \GuzzleHttp\Client();
        try {
            $response = $client->request($method, $url, ['query' => $options]);
            if ($response->getStatusCode() == 200) {
                $response = $response->getBody()->getContents();
                $result = json_decode($response, true);
                if (empty($result['status'])) {
                    Blogger::getLogger("add_crisis_escalation_error")->error("上报失败:" . $result['msg'], ['result' => $result, 'url' => $url, 'require_data' => $options]);
                    throw new \RuntimeException("上报失败:" . $result['msg']);
                }
                Blogger::getLogger("add_crisis_escalation_info")->info("上报时间成功", ['result' => $result, 'url' => $url, 'require_data' => $options]);
                return true;
            }
            Blogger::getLogger("add_crisis_escalation_error")->error("上报失败:请求失败");
            throw new \RuntimeException("上报失败:请求失败");
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            Blogger::getLogger("add_crisis_escalation_error")->error("上报失败异常" . $e->getMessage());
            throw new \RuntimeException("上报失败:" . $e->getMessage());
        }
    }
}
/**
 * 请求接口
 */
if (!function_exists('makeClientRequestByReferral')) {
    function makeClientRequestByReferral($options, $url, $method)
    {
        $client = new \GuzzleHttp\Client();
        try {
            $response = $client->request($method, $url, ['query' => $options]);
            if ($response->getStatusCode() == 200) {
                $response = $response->getBody()->getContents();
                $result = json_decode($response, true);
                if (empty($result['status'])) {
                    Blogger::getLogger("referral_edu_error")->error("上报失败:" . $result['msg'], ['result' => $result, 'url' => $url, 'require_data' => $options]);
                    throw new \RuntimeException("上报失败:" . $result['msg']);
                }
                Blogger::getLogger("referral_edu_info")->info("上报时间成功", ['result' => $result, 'url' => $url, 'require_data' => $options]);
                return true;
            }
            Blogger::getLogger("referral_edu_error")->error("上报失败:请求失败");
            throw new \RuntimeException("上报失败:请求失败");
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            Blogger::getLogger("referral_edu_error")->error("上报失败异常" . $e->getMessage());
            throw new \RuntimeException("上报失败:" . $e->getMessage());
        }
    }
}
/**
 * 导出excel信息 省市区
 */
if (!function_exists('exportExcelInfoThree')) {
    function exportExcelInfoThree($title, $data, $fileName = 'xxxx.xlsx')
    {

//        $data = [
//            [1, 'jack', 10],
//            [2, 'mike', 12],
//            [3, 'jane', 21],
//            [4, 'paul', 26],
//            [5, 'kitty', 25],
//            [6, 'yami', 60],
//        ];
//
//        $title = ['编号', '姓名', '年龄'];

        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        //设置工作表标题名称
        $worksheet->setTitle('工作表格');

        $styleArray1 = [
//            'font' => ['bold' => true],
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,// 水平居中
                'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER //垂直居中
            ],
            'borders' => [
                'outline' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
//                    'color' => ['argb' => 'ffffff'],
                ],
            ],
        ];
        //表头
        //设置单元格内容
        $titleColumnTwo = "A";
        foreach ($title as $key => $value) {
            $worksheet->getStyle($titleColumnTwo . "2")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('A6C9E8');// 设置背景色
            $worksheet->getStyle($titleColumnTwo . "2")->applyFromArray($styleArray1);// 加粗，水平居中，边框线颜色

            $worksheet->setCellValueByColumnAndRow($key + 1, 2, $value);
            $titleColumnTwo++;
        }

        $styleArray = [
            'font' => ['bold' => true],
            'alignment' => [
                'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,// 水平居中
                'vertical' => \PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER //垂直居中
            ],
            'borders' => [
                'outline' => [
                    'borderStyle' => \PhpOffice\PhpSpreadsheet\Style\Border::BORDER_THIN,
//                    'color' => ['argb' => 'ffffff'],
                ],
            ],
        ];
        //合并单元格
        $worksheet->setCellValue('B1', '参评学生');
        $worksheet->getStyle('B1')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
        $worksheet->getStyle('B1')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('A6C9E8');// 设置背景色


        $worksheet->getStyle('B1')->applyFromArray($styleArray);// 加粗，水平居中，边框线颜色


        //合并单元格
        $worksheet->mergeCells('C1:F1');
        $worksheet->setCellValue('C1', '心理健康水平');
        $worksheet->getStyle('C1')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
        $worksheet->getStyle('C1')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('A6C9E8');// 设置背景色
        $worksheet->getStyle('C1:F1')->applyFromArray($styleArray);// 加粗，水平居中，边框线颜色

        $worksheet->getStyle('A1')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('A6C9E8');// 设置背景色
        $worksheet->getStyle('A1')->applyFromArray($styleArray);// 加粗，水平居中，边框线颜色
        $worksheet->getStyle("A2")->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('A6C9E8');// 设置背景色

        $worksheet->mergeCells('G1:O1');
        $worksheet->setCellValue('G1', '心理健康问题');
        $worksheet->getStyle('G1')->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
        $worksheet->getStyle('G1')->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('A6C9E8');// 设置背景色
        $worksheet->getStyle('G1:O1')->applyFromArray($styleArray);// 加粗，水平居中，边框线颜色


        $totalNumber = count($data) + 3 + 1 + 3;
        $worksheet->mergeCells('A' . $totalNumber . ':O' . $totalNumber);
        $worksheet->setCellValue('A' . $totalNumber, "注：\n有效作答人数是指删除作答可靠性较低、作答时长过短的学生之后的人数；\n本次测评将学生的心理健康水平分为四类：适应良好，适应问题（一般心理问题），严重问题（严重心理问题），危机问题（高危问题）。");
        $worksheet->getRowDimension($totalNumber)->setRowHeight(56);//设置行高

        $worksheet->getStyle('A' . $totalNumber . ':O' . $totalNumber)->getAlignment()->setWrapText(true);


        $row = 3; //从第二行开始
        foreach ($data as $item) {
            $column = 1;
            $columnTwo = "A";
            foreach ($item as $value) {
                if ($columnTwo == "A") {
                    $worksheet->getStyle($columnTwo . $row)->getFill()->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)->getStartColor()->setARGB('A6C9E8');// 设置背景色

                }
                $worksheet->setCellValueByColumnAndRow($column, $row, $value);
                $column++;
                $columnTwo++;
            }
            $row++;
        }
        //2.输出到浏览器
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx'); //按照指定格式生成Excel文件

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
        header('Content-Disposition: attachment;filename="' . $fileName . '"');
        header('Cache-Control: max-age=0');
        // If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');

        // If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0
        $writer->save('php://output');
        //释放
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);

    }
}
/**
 * 文雅静
 * 发送data数据
 */
if (!function_exists('makeClientPyQueryRequest')) {
    function makeClientPyQueryRequest($options, $url, $method)
    {
        $client = new \GuzzleHttp\Client();
        try {
            $response = $client->request($method, $url, ['query' => $options]);
            $result = [];
            if ($response->getStatusCode() == 200) {
                $result = json_decode($response->getBody()->getContents());
                Blogger::getLogger('py-wen-success')->info("请求更新成功：" . json_encode($response));
            }
            return $result;
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            Blogger::getLogger('py-wen-error')->info("请求更新失败：" . json_encode($e->getMessage()));
            return "error";
        }
    }
}
/**
 * 获取当前日期
 */
if (!function_exists('getCurrentDateTime')) {
    function getCurrentDateTime()
    {
        return date("Ymd", time());
    }
}
/**
 * 报告
 * 发送data数据
 */
if (!function_exists('makeClientReportRequest')) {
    function makeClientReportRequest($options, $url, $method)
    {
        $client = new \GuzzleHttp\Client();
        try {
            $response = $client->request($method, $url, ['query' => $options,'timeout'=>3]);

            $result = [];
            if ($response->getStatusCode() == 200) {
                $result = json_decode($response->getBody()->getContents());
                Blogger::getLogger('make_client_report_request_success')->info("请求更新成功：", ['result' => $result]);
            }
            return $result;
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            Blogger::getLogger('make_client_report_request_error')->info("请求更新失败：", ['error' => $e->getMessage()]);
            return false;
        }
    }
}


/**
 * 深圳报告（区域ID）
 */
if (!function_exists('reportArea')) {
    /**
     * 深圳报告
     * @param $areaId
     * @return bool
     */
    function reportArea($areaId)
    {
        if(in_array($areaId,config('report_common')['area_ids'])){
            return true;
        }
        return false;
    }
}




if (!function_exists('transFormArray')) {
    /**
     * @param $data
     * @return array
     */
     function transFormArray($data){
        $newData = [];
        foreach ($data as $key=>$datum){
            $newData[$key] = $datum;
        }
        return $newData;
    }
}



if (!function_exists('transFormArrayAs')) {
    /**
     * @param $data
     * @return array
     */
    function transFormArrayAs($data){
        $newData = [];
        foreach ($data as $key=>$datum){

            if ($key>7){
               continue;
            }
            $newData[$key] = space($datum);
        }
        return $newData;
    }
}

/**
 * 数据库链接
 */
if (!function_exists('DbConnect')) {
    function DbConnect($startTime)
    {
        $semesterDateByTime = (new DbConfigService())->getSemesterDateByTime($startTime);
        $DbConnect = testTimeList($semesterDateByTime);
        return $DbConnect['db_connection'];
    }
}






/**
 * 成都报告（区域ID）
 */
if (!function_exists('chengDuArea')) {
    /**
     * 成都报告
     * @param $areaId
     * @return bool
     */
    function chengDuArea($areaId)
    {
        if(in_array($areaId,config('report_common')['chengdu_ids'])){
            return true;
        }
        return false;
    }
}

/**
 * 成都报告（区域ID）
 */
if (!function_exists('reportWLXY')) {
    /**
     * 成都报告
     * @param $areaId
     * @return bool
     */
    function reportWLXY($areaId)
    {
        if(in_array($areaId,[51010055])){
            return true;
        }
        return false;
    }
}




/**
 * 请求数据需携带对方token
 * @package
 */
if (!function_exists('javaClientGet')) {
    function javaClientGet($options, $url, $method)
    {
        $client = new \GuzzleHttp\Client();
        $authToken = userInfo()->auth_token;
        try {
            $response = $client->request($method, $url, [
                'query' =>$options,
                'timeout' => 5,
                'headers' => [
                    'token' => "Bearer $authToken"
                ]
            ]);
            if ($response->getStatusCode() == 200) {
                return \GuzzleHttp\json_decode($response->getBody()->getContents());
            }
            return false;
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            Blogger::getLogger('report_json_content')->info("获取复检报告内容失败：", ['error' => $e->getMessage()]);
            return false;
        }
    }
}

/**
 * 优化报告
 */
if (!function_exists('timeYh')) {
    function timeYh($startTime)
    {
        if($startTime >= config('main')['report_recheck_version_time_yh']){
            return true;
        }
        return false;
    }
}


/**
 * 优化报告
 */
if (!function_exists('timeRecheck2024')) {
    function timeRecheck2024($startTime)
    {
        if($startTime >= config('report_common.time_recheck_v2024')){
            return true;
        }
        return false;
    }
}





if (!function_exists('chengduNJ')) {
    function chengduNJ($city)
    {
        if(in_array($city,[
            511000,
            130900,
            130100,
            130200,
            130300,
            130400,
            130500,
            130600,
            130700,
            130800,
            130900,
            131000,
            131100,
        ])){
            return true;
        }
        return false;
    }
}

/**
 * 新版报告
 */
if (!function_exists('schoolReportV8')) {

    function schoolReportV8($time)
    {
        if($time > config('main')['school_report_time_version']){
            return true;
        }
        return false;
    }
}

/**
 * 新版报告
 */
if (!function_exists('schoolReportV7')) {

    function schoolReportV7($time,$areaId)
    {
        if($time > config('main')['school_report_time_version'] &&   in_array($areaId,config('report_common')['chengdu_ids']) ){
            return true;
        }
        return false;
    }
}

/**
 * 导出excel信息
 */
if (!function_exists('exportCsv')) {
    function exportCsv($title, $data,$outputPath)
    {

//        $data = [
//            [1, 'jack', 10],
//            [2, 'mike', 12],
//            [3, 'jane', 21],
//            [4, 'paul', 26],
//            [5, 'kitty', 25],
//            [6, 'yami', 60],
//        ];
//
//        $title = ['编号', '姓名', '年龄'];

        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        //设置工作表标题名称
        $worksheet->setTitle('工作表格');
        //表头
        //设置单元格内容
        foreach ($title as $key => $value) {
            $worksheet->setCellValueByColumnAndRow($key + 1, 1, $value);
        }

        $row = 2; //从第二行开始
        foreach ($data as $item) {
            $column = 1;

            foreach ($item as $value) {
                $worksheet->setCellValueByColumnAndRow($column, $row, $value);
                $column++;
            }
            $row++;
        }
        //保存到指定目录
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Csv'); //按照指定格式生成Excel文件

        //"/Users/mengqiang/Downloads/rservice/read/".$fileName
        $writer->save($outputPath);
        //释放
        $spreadsheet->disconnectWorksheets();
        unset($spreadsheet);
    }

}



/**
 * 新版报告
 */
if (!function_exists('classReportV5')) {

    function classReportV5($time,$areaId)
    {
        if($time > config('main')['school_report_time_version'] &&   in_array($areaId,config('report_common')['class_chengdu_ids']) ){
            return true;
        }
        return false;
    }
}




/**
 * 成都报告（区域ID）
 */
if (!function_exists('classArea')) {
    /**
     * 成都报告
     * @param $areaId
     * @return bool
     */
    function classArea($areaId)
    {
        if(in_array($areaId,config('report_common')['class_chengdu_ids'])){
            return true;
        }
        return false;
    }
}


/**
 *  ---- 获取 ----
 */
if (!function_exists('testTimeList')) {
    function testTimeList($input)
    {
//        $input['semester_start_time'] = "2023-09-01";
//        $input['semester_end_time'] = "2024-01-31";
        $input['semester_start_time']= ($input['semester_start_time'])??"";
        $input['semester_end_time']= ($input['semester_end_time'])??"";
        $input['db_connection']=(new DbConfigService())->getDbConnect($input['semester_start_time']);
        return $input;
    }
}
/**
 *  ---- 获取 ----
 */
if (!function_exists('proTimeList')) {
    function proTimeList($input)
    {
//        $input['semester_start_time'] = "2023-09-01";
//        $input['semester_end_time'] = "2024-01-31";
        $input['semester_start_time']= ($input['semester_start_time'])??"";
        $input['semester_end_time']= ($input['semester_end_time'])??"";
        $input['db_connection']=(new DbConfigService())->getDbConnect($input['semester_start_time']);
        return $input;
    }
}





/**
 * 模拟接口数据
 */
if (!function_exists('checkJavaRecheckFromDataQuery')) {
    function checkJavaRecheckFromDataQuery($options, $url, $method,$authToken)
    {
        $client = new \GuzzleHttp\Client();
        try {
            $response = $client->request($method, $url, [
                'query' => $options,
                'timeout' => 5,
                'headers' => [
                    'token' => "Bearer $authToken"
                ]
            ]);
            if ($response->getStatusCode() == 200) {
                return \GuzzleHttp\json_decode($response->getBody()->getContents());
            }
            return false;
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            return false;
        }
    }
}


if (!function_exists('mobilePermission')) {
    function mobilePermission()
    {
        return  request()->get('mobilePermission');
    }
}

/**
 * 模拟接口数据
 */
if (!function_exists('checkJavaRecheckFromNotDataQuery')) {
    function checkJavaRecheckFromNotDataQuery($options, $url, $method,$authToken)
    {
        $client = new \GuzzleHttp\Client();
        try {
            $response = $client->request($method, $url, [
                'query' => $options,
                'timeout' => 5,
                'headers' => [
//                    'token' => "Bearer $authToken"
                ]
            ]);
            if ($response->getStatusCode() == 200) {
                return \GuzzleHttp\json_decode($response->getBody()->getContents());
            }
            return false;
        } catch (\GuzzleHttp\Exception\RequestException $e) {
            return false;
        }
    }
}
/**
 * 导出excel信息
 */
if (!function_exists('exportExcelInfoConsole')) {
    function exportExcelInfoConsole($title, $data, $fileName = 'xxxx.xlsx')
    {

//        $data = [
//            [1, 'jack', 10],
//            [2, 'mike', 12],
//            [3, 'jane', 21],
//            [4, 'paul', 26],
//            [5, 'kitty', 25],
//            [6, 'yami', 60],
//        ];
//
//        $title = ['编号', '姓名', '年龄'];

        $spreadsheet = new \PhpOffice\PhpSpreadsheet\Spreadsheet();
        $worksheet = $spreadsheet->getActiveSheet();
        //设置工作表标题名称
        $worksheet->setTitle('工作表格');

        //表头
        //设置单元格内容
        foreach ($title as $key => $value) {
            $worksheet->setCellValueByColumnAndRow($key + 1, 1, $value);
        }

        $row = 2; //从第二行开始
        foreach ($data as $item) {
            $column = 1;

            foreach ($item as $value) {
                $worksheet->setCellValueByColumnAndRow($column, $row, $value);
                $column++;
            }
            $row++;
        }
        //2.输出到浏览器
        $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx'); //按照指定格式生成Excel文件
        $writer->save($fileName);

//        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
//        header('Content-Disposition: attachment;filename="' . $fileName . '"');
//        header('Cache-Control: max-age=0');
//        // If you're serving to IE 9, then the following may be needed
//        header('Cache-Control: max-age=1');
//
//        // If you're serving to IE over SSL, then the following may be needed
//        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
//        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
//        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
//        header('Pragma: public'); // HTTP/1.0
//        $writer->save('php://output');
//        //释放
//        $spreadsheet->disconnectWorksheets();
//        unset($spreadsheet);

    }

}

